#coding=utf-8
#导入相关库
from tkinter import *
import pyaudio
import wave
import requests
import json
import pandas
from pyttsx3 import *
from aip import AipSpeech
import jieba
import os
current_dir = os.path.dirname(__file__)

#读入全国各省对应市县名称
xlsx = os.path.join(current_dir, 'cityinfo.csv')
df = pandas.read_csv(xlsx,encoding='utf-8')

#主程序：实现腾讯天气信息爬取并根据提示自动播报目标城市天气
class weather_aispeak():
    def __init__(self):
        # 设置百度语音识别接口
        Appid = '173679c05'  #这里修改成你自己的
        self.API_Key = 'flc88CKX43YeAxaVIgSsssYVxBG'  #这里修改成你自己的
        self.Secret_Key = '1VGa1ISBcAafZYsWLs981YWEssimgSxxxvhnW' #这里修改成你自己的
        self.client = AipSpeech(Appid, self.API_Key, self.Secret_Key)

    # 用pyaudio库录制音频
    def audio_record(self,out_file, rec_time):
        CHUNK = 1024
        FORMAT = pyaudio.paInt16  # 16bit编码格式
        CHANNELS = 1  # 单声道
        RATE = 16000  # 16000采样频率
        p = pyaudio.PyAudio()
        # 创建音频流
        stream = p.open(format=FORMAT, channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK)
        frames = []
        # 录制音频数据
        for i in range(0, int(RATE / CHUNK * rec_time)):
            data = stream.read(CHUNK)
            frames.append(data)
        # 录制完成
        stream.stop_stream()
        stream.close()
        p.terminate()
        # 保存音频文件
        wf = wave.open(out_file, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

    # 调用百度语音API完成语音到文字转换
    def aip_wav2texts(self):
        # dev_pid String  默认1537(普通话 输入法模型)
        file=os.path.join(current_dir, 'j.wav')
        with open(file, 'rb') as fp:
            content = fp.read()
        result = self.client.asr(content, 'wav', 16000,
                            {"dev_pid": 1537,})
        if result["err_msg"] == "success.":
            return result["result"]
        else:
            return ""

    #爬虫来获取目标省市的天气信息并组织成相应的话语字符串
    def weather_access(self,province=None,city=None):
        # province = df[df['市'].str.contains(city)]['省'].values[0]
        # cities = ['北京', '上海', '重庆', '天津']
        # if city in cities: province = city
        url = 'https://wis.qq.com/weather/common?source=pc&weather_type=observe%7Cforecast_1h%7Cforecast_24h%7Cindex%7Calarm%7Climit%7Ctips%7Crise\
        &province='+province+'&city='+city+'&_=1618230836535'
        headers={
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.75'
        }
        weather = json.loads(requests.get(url,headers=headers).text)['data']['observe']
        friend_info = json.loads(requests.get(url,headers=headers).text)['data']['index']
        weather_tom = json.loads(requests.get(url,headers=headers).text)['data']['forecast_24h']
        detail = friend_info['airconditioner']['detail']
        carwash = friend_info['carwash']['detail']
        time = weather['update_time']
        weather_c = weather['weather']
        degree = weather['degree']
        humidity = weather['humidity']
        tom_maxdegree = weather_tom['3']['max_degree']
        tom_mindegree = weather_tom['3']['min_degree']
        tom_weather = weather_tom['3']['day_weather']
        tom_weather_wind_direction = weather_tom['3']['day_wind_direction']
        tom_weather_wind_power = weather_tom['3']['day_wind_power']
        year = time[:4]
        month = time[4:6]
        if '0' in month:
            month = month[-1]
        date = time[6:8]
        if '0' in date:
            date = date[-1]
        hour = time[8:10]
        if hour[0]=='0':
            hour = hour[1]
        elif hour[1]=='0':
            hour = hour
        minute = time[10:12]
        if '0' in minute[-2]:
            minute = minute[-1]
        says = '今天是'+year+'年'+month+'月'+date+'日'
        says+= '  ;根据气象台'+hour+'点'+minute+'分'+'发布信息:'
        says+= '  ;现在'+city+'的天气状况为:'+weather_c+' '
        says+= '  ;室外温度:'+degree+ ' '
        says+= '  ;当前湿度:'+humidity+ ' '
        says+= ' 同时:'+carwash
        says+= '; 明日天气状况：'+tom_weather
        says+= '; 最高温度：'+tom_maxdegree
        says+= '; 最低温度：'+tom_mindegree
        says+= tom_weather_wind_direction+'; 风力：'+tom_weather_wind_power
        says+='天气播报完毕，别忘记关注稻谷同时给我点赞哦'
        return says

#播报天气预报信息
def wea_speak():
    speak("你想知道国内哪个城市的天气呢？")
    wa=weather_aispeak()
    wa.audio_record('j.wav',5)
    words = wa.aip_wav2texts()
    res = jieba.tokenize(words[0])
    words_li = [item[0] for item in res]
    print(words_li)
    for item in words_li:
        if item in df['市'].values:
            city=item
            province = df[df['市'].str.contains(city)]['省'].values[0]
        elif item in ['北京', '上海', '重庆', '天津']:
            city=item
            province=city
    speak(wa.weather_access(province=province,city=city))

#窗口视图呈现部分
class waUI(Tk):
    def __init__(self):
        super().__init__()
        self.geometry('500x400')
        self.title('天气预报问答小程序 -- 稻谷编程')
        self.resizable(0,0)
        self.photo = PhotoImage(file=current_dir+"/clip2.gif")
        self.widgets()

    def widgets(self):
        label = Label(self)
        label['font']=("华文行楷", 20)
        label['image']=self.photo
        label['text']=''
        label.pack()
        btn = Button(self)
        btn['width']= 22
        btn['height']= 2
        btn['text']="问天气,点我一下就行"
        btn['font']=("黑体", 18)
        btn['bg']='#f60'
        btn['fg']='yellow'
        btn['relief']='groove'
        btn['command'] = self.btnAction
        btn.pack()
        label2 = Label(self)
        label2['font'] = ("楷体", 14)
        label2['text'] = '直接说一个地级市，就可以语音播报当地的天气哦'
        label2.pack()

    def btnAction(self):
        wa = wea_speak()

#运行主程序
if __name__=='__main__':
    app=waUI()
    app.mainloop()